package com.txt.aspect;

import com.txt.annotion.Txt;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
public class AopAspect {

    @Pointcut("@annotation(com.txt.annotion.Txt)")
    public void pointCut() {}

    @Before("pointCut()")
    public void before(JoinPoint joinPoint) {
        // 获取当前方法的签名
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        // 获取方法名
        String methodName = signature.getName();
        // 获取方法的注解
        Txt txt = signature.getMethod().getAnnotation(Txt.class);

        // 获取当前请求的HttpServletRequest对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            System.out.println("请求的 URL: " + request.getRequestURL().toString());
        }
    }

    @After("pointCut()")
    public void after() {
        System.out.println("after...");
    }

    @AfterThrowing(pointcut = "pointCut()", throwing = "ex")
    public void afterThrowing(Throwable ex) {
    }
}
